package com.ruoyi.core.config.utils;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.model.WxUser;
import com.ruoyi.common.enums.DeviceType;
import com.ruoyi.common.enums.UserType;
import com.ruoyi.common.helper.LoginHelper;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.core.config.vo.LoginVo;
import com.ruoyi.core.domain.vo.UserVo;
import com.ruoyi.core.service.IUserService;
import org.apache.commons.lang3.StringUtils;

import static com.ruoyi.common.helper.LoginHelper.getUserId;

/**
 * 微信授权登录工具类
 */
public class WxUtil  {

    public static UserVo getUserVoByToken(){
        try {
            Long userId = getUserId();
            if(ObjectUtil.isNotNull(userId)){
                //在工具类中引用service
                return SpringUtils.getBean(IUserService.class).queryById(userId);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 设置或者刷新 loginUser 缓存 WxUser
     * @param userVo
     * @param needLogin
     */
    public static  void  refreshWxUser(UserVo userVo, boolean needLogin){
        WxUser wxUser  = BeanUtil.toBean(userVo, WxUser.class);
        wxUser.setUserId(userVo.getId());
        wxUser.setUsername(userVo.getNickname());
        wxUser.setUserType(UserType.APP_USER.getUserType()); //app端用户
         if(needLogin){
             LoginHelper.loginByDevice(wxUser, "0".equals(userVo.getUtype())? DeviceType.MP :  DeviceType.XCX);
         }else{
             LoginHelper.setLoginUser(wxUser);
         }
    }

    /**
     * 根据是否有昵称返回登录结果
     * @param userVo
     * @return
     */
    public static R<LoginVo> authMsg(UserVo userVo){
        if(StringUtils.isBlank(userVo.getNickname())){
            return R.fail("非首次未授权",new LoginVo(StpUtil.getTokenValue(),userVo, "0"));
        }
        return R.ok("登录成功",new LoginVo(StpUtil.getTokenValue(),userVo ,"0"));
    }
}
